package com.mine.java.future;

import java.util.concurrent.CompletableFuture;

/**
 * @author weixiao
 * @date 2025/3/24 10:24
 */
public class CompletableFutureDemo01 {

    public static void main(String[] args) {
        demo01();
    }

    public static void demo01() {
        PrintUtils.print("小明来到餐厅，并完成点菜");
        CompletableFuture<String> scf = CompletableFuture.supplyAsync(() -> {
            PrintUtils.print("厨师炒菜");
            PrintUtils.print("厨师盛饭");
            PrintUtils.sleep(2000);
            return "饭好了";
        });
        PrintUtils.print("小明一边等饭好了，一边玩游戏");
        PrintUtils.print(scf.join() + ",小明开始吃饭");
    }

    public static void demo02() {
        PrintUtils.print("小明来到餐厅，并完成点菜");
        CompletableFuture<String> scf = CompletableFuture.supplyAsync(() -> {
            PrintUtils.print("厨师炒菜");
            return "西红柿鸡蛋";
        }).thenApplyAsync(str -> {
            PrintUtils.print("服务员盛饭");
            return str + "和饭都好了";
        });
        PrintUtils.print("小明一边等饭好了，一边玩游戏");
        PrintUtils.print(scf.join() + ",小明开始吃饭");
    }

    public static void demo03() {
        PrintUtils.print("小明在公交站台等车");
        CompletableFuture<String> scf = CompletableFuture.supplyAsync(() -> {
            PrintUtils.sleep(800);
            PrintUtils.print("700路车来了");
            return "700";
        }).applyToEither(CompletableFuture.supplyAsync(() -> {
            PrintUtils.sleep(300);
            PrintUtils.print("800路车来了");
            return "800";
        }), str -> str);
        PrintUtils.print(String.format("%s来了，小明坐车回家", scf.join()));
    }

    public static void demo04() {
        PrintUtils.print("小明来到餐厅，并完成点菜");
        CompletableFuture<String> scf = CompletableFuture.supplyAsync(() -> {
            PrintUtils.print("厨师炒菜");
            return "西红柿鸡蛋";
        }).thenCompose(str -> CompletableFuture.supplyAsync(() -> {
            PrintUtils.print("服务员盛饭");
            return str + "和饭都好了";
        }));
        PrintUtils.print("小明一边等饭好了，一边玩游戏");
        PrintUtils.print(scf.join() + ",小明开始吃饭");
    }
}
